<template>
  <div>
    <a-form :form="form">
      <div class="header">
        <h3>一、基本信息</h3>
        <div class="operate">
          <div>
            <transition name="slide-fade">
              <a-button type="primary" @click="handleReduce" v-show="!disabled"
                >还原默认</a-button
              >
            </transition>
            <a-button type="primary" v-if="disabled" @click="disabled = false"
              >修改</a-button
            >
            <a-button type="primary" @click="handleEdit" v-else
              >保存修改</a-button
            >
          </div>
        </div>
      </div>
      <a-form-item
        label="行业编号"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input
          v-if="!disabled"
          disabled
          :placeholder="check.sn"
          v-decorator="[
            'number',
            {
              initialValue: check.number,
            },
          ]"
        />
        <div v-else>{{ check.number || "暂无编号" }}</div>
      </a-form-item>
      <a-form-item
        label="行业名称"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input
          v-if="!disabled"
          placeholder="行业名称"
          v-decorator="[
            'name',
            {
              rules: [{ required: true, message: '请输入行业名称' }],
              initialValue: check.name,
            },
          ]"
        />
        <div v-else>{{ check.name }}</div>
      </a-form-item>
      <a-form-item
        label="宣传语1"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input
          v-if="!disabled"
          placeholder="请输入宣传语1"
          v-decorator="[
            'propagate1',
            {
              initialValue: check.propagate1,
              rules: [
                { required: true, message: '请输入宣传语1' },
                { validator: validatePropagate },
              ],
              validateTrigger: 'blur',
            },
          ]"
        />
        <div v-else>{{ check.propagate1 }}</div>
      </a-form-item>
      <a-form-item
        label="宣传语2"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input
          v-if="!disabled"
          placeholder="请输入宣传语2"
          v-decorator="[
            'propagate2',
            {
              initialValue: check.propagate2,
              rules: [
                { required: true, message: '请输入宣传语2' },
                { validator: validatePropagate },
              ],
              validateTrigger: 'blur',
            },
          ]"
        />
        <div v-else>{{ check.propagate2 }}</div>
      </a-form-item>
      <a-form-item label="缩略图" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <div>
          <span v-if="!Boolean(check.image)">暂无数据</span>
          <img v-else :src="image" width="150" height="180" />
        </div>
        <a-upload
          v-if="!disabled"
          name="file"
          :showUploadList="false"
          :multiple="false"
          :customRequest="this.handleUploadImage"
        >
          <a-button type="primary"> <a-icon type="upload" />点击上传</a-button>
        </a-upload>
      </a-form-item>
      <a-form-item label="视频" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <div>
          <span v-if="!Boolean(check.video)">暂无视频</span>
          <video
            v-else
            :src="video"
            width="300"
            height="200"
            controls="controls"
          >
            您的浏览器不支持 video 标签。
          </video>
        </div>
        <a-upload
          v-if="!disabled"
          name="file"
          :showUploadList="false"
          :multiple="false"
          :customRequest="this.handleUploadVideo"
        >
          <a-button type="primary"> <a-icon type="upload" />点击上传</a-button>
        </a-upload>
      </a-form-item>
      <!-- <a-form-item label="是否显示" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-radio-group :disabled="disabled" v-decorator="[
                    'status',
                    {
                        initialValue: check.status
                    }
                ]">
                    <a-radio :value="1">
                    显示
                    </a-radio>
                    <a-radio :value="0">
                    隐藏
                    </a-radio>
                </a-radio-group>
            </a-form-item> -->
    </a-form>

    <div>
      <h3>二、对应巡检</h3>
      <a-form
        :form="searchForm"
        layout="inline"
        @submit.prevent="onSearchFormSubmit"
        :style="{ marginBottom: '20px' }"
        id="service-menu-search"
      >
        <div class="service-menu-query">
          <a-form-item>
            <a-button
              @click="handleSort(-1)"
              style="width: 50px"
              type="primary"
            >
              <a-icon type="arrow-up" />
            </a-button>
          </a-form-item>
          <a-form-item>
            <a-button @click="handleSort(1)" style="width: 50px" type="primary">
              <a-icon type="arrow-down" />
            </a-button>
          </a-form-item>
          <a-form-item :style="{ flexGrow: 1 }">
            <a-button @click="handleShowAddCheck" type="primary" icon="plus"
              >添加</a-button
            >
          </a-form-item>
        </div>
      </a-form>
      <a-table
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          type: 'radio',
        }"
        :columns="columns"
        :dataSource="data"
        rowKey="id"
        :pagination="pagination"
        bordered
      >
        <template slot="indexRender" slot-scope="text, record, index">
          {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
        </template>
        <span slot="industry" slot-scope="text, record">
          <template v-if="record.industry && record.industry.length > 0">
            <div v-for="item in record.industry" :key="item.id">
              {{ item.name }}
            </div>
          </template>
          <span v-else>暂未添加</span>
        </span>
        <span slot="unit" slot-scope="text, record">
          <template>
            {{ record.unit | filterUnit }}
          </template>
        </span>
        <span slot="video" slot-scope="text, record">
          <template v-if="record && record.video">
            <a-icon
              @click.stop.prevent="handlePlayVideo(record)"
              :style="{ fontSize: '20px', color: '#08c', cursor: 'pointer' }"
              type="video-camera"
            />
          </template>
          <span v-else>暂未添加</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <img
            class="delete-icon"
            @click.stop.prevent="showdel(record)"
            src="./../../assets/images/delete.svg"
            alt=""
          />
        </span>
      </a-table>
    </div>

    <a-modal centered v-model="videoVisible" title="播放视频">
      <video
        width="470"
        height="300"
        :src="selectRecord.video"
        controls="controls"
      >
        您的浏览器不支持 video 标签。
      </video>
      <div slot="footer">
        <a-button
          @click.stop.prevent="videoVisible = false"
          style="display: inline-block; margin: 0 auto"
          type="primary"
          >关闭</a-button
        >
      </div>
    </a-modal>

    <!-- 添加对应巡检 -->
    <a-modal centered v-model="addCheckVisible" title="添加巡检">
      <a-input
        placeholder="请选择对应巡检"
        v-model="keywords"
        @input="searchkey"
      />
      <div class="keywrod-wrap">
        <ul>
          <li v-for="item in inspectlist" :key="item.id" @click="subkey(item)">{{item.name}}</li>
        </ul>
      </div>
      <!-- <a-select
        show-search
        style="width: 100%"
        
        :filterOption="handleFilterOption"
        v-model="checkIds"
      >
        <a-select-option
          :name="inspect.name"
          :value="inspect.id"
          v-for="inspect in inspectList"
          :key="inspect.id"
        >
          {{ inspect.name }}
        </a-select-option>
      </a-select> -->
      <div slot="footer" class="footer-wrap">
        <a-button @click="addCheckVisible = false" type="warning"
          >取消</a-button
        >
        <a-button @click="handleAddCheck" type="primary">确认</a-button>
      </div>
    </a-modal>
    <!-- 添加对应巡检end -->

    <!-- 删除对应巡检 -->
    <div class="moadel-wrap">
      <a-modal title="删除" :visible="isdel" @cancel="handleCancel">
        <template slot="footer">
          <a-button type="warning" @click="handleCancel">取消</a-button>
          <a-button type="primary" @click="handleDelete">确定</a-button>
        </template>
        <p>是否删除巡检-{{ deldata.number }}?</p>
      </a-modal>
    </div>
    <!-- 删除对应巡检 end -->
  </div>
</template>

<script>
import config from "@/api/config";

export default {
  name: "check-update",
  data() {
    return {
      id: undefined,
      check: {},
      disabled: true,
      cateMap: {},
      keywords:'',//存放用户搜索的内容
      form: this.$form.createForm(this),
      labelCol: { lg: { span: 7 }, sm: { span: 7 } },
      wrapperCol: { lg: { span: 10 }, sm: { span: 17 } },

      video: "",
      image: "",

      searchForm: this.$form.createForm(this),

      data: [],
      deldata: {},
      isdel: false,
      columns: [
        {
          title: "序号",
          scopedSlots: { customRender: "indexRender" },
          align: "center",
        },
        { title: "巡检编号", dataIndex: "number", align: "center" },
        { title: "巡检名称", dataIndex: "name", align: "center" },
        { title: "价格", dataIndex: "price", align: "center" },
        {
          title: "单位",
          scopedSlots: { customRender: "unit" },
          align: "center",
        },
        {
          title: "视频",
          scopedSlots: { customRender: "video" },
          align: "center",
        },
        {
          title: "操作",
          scopedSlots: { customRender: "action" },
          align: "center",
        },
      ],
      pagination: {
        current: 1,
        total: 0,
        pageSize: 10,
        showQuickJumper: true,
        onChange: (page, size) => {
          this.handleChange(page, size);
        },
      },
      videoVisible: false,
      selectRecord: {},
      selectedRowKeys: [],
      inspectList: [],
      inspectlist:[],
      addCheckVisible: false,
      check: undefined,
    };
  },
  filters: {
    filterUnit(val) {
      if (val === 1) {
        return "每点*8h";
      } else if (val === 2) {
        return "公里";
      } else {
        return "平方公里";
      }
    },
  },
  methods: {
    //关闭删除框
    handleCancel() {
      this.isdel = false;
    },
    //定义宣传语的规则
    validatePropagate(rule, val, callback) {
      if (val.length > 9) {
        callback("请勿超过9个字");
      } else {
        callback();
      }
    },
    async getDetail() {
      let { id } = this,
        { data } = await this.http("get", `/industry/view/${id}`);
      this.check = data || {};

      this.image = this.check.image;
      this.video = this.check.video;
    },
    async getInspection() {
      let { id } = this,
        { data } = await this.http("get", `/inspection/searchInpsection`, {
          industryId: id,
        });
      this.data = data || [];

      if (this.data && this.data.length) {
        this.data.sort((a, b) => Number(b.sort) - Number(a.sort));
      }
    },
    handleEdit() {
      this.form.validateFields(async (err, values) => {
        if (!err) {
          console.log("values:", values, this.url);
          values.image = this.image;
          values.video = this.video;
          values.id = this.check.id;
          // this.url || this.check.video
          let { status, message } = await this.http(
            "put",
            "/industry/update",
            values
          );
          if (status === 1) {
            this.$message.success("修改成功", 1);
            await this.getDetail();
            this.disabled = true;
          } else {
            this.$message.error(message, 1);
          }
        }
      });
    },
    handleReduce() {
      let { sn, name, propagate1, propagate2 } = this.check;
      this.form.setFieldsValue({
        sn,
        name,
        propagate1,
        propagate2,
      });
      this.image = this.check.image;
      this.video = this.check.video;
      this.disabled = true;
    },
    async handleUploadImage(args) {
      let params = new FormData();
      params.append("uploadFile", args.file);
      let {
        data: { filePath },
      } = await this.http("post", config.uploadURL, params);
      this.image = filePath;
      return args.onSuccess({ code: 200 }, args.file);
    },
    async handleUploadVideo(args) {
      let params = new FormData();
      params.append("uploadFile", args.file);
      let {
        data: { filePath },
      } = await this.http("post", config.uploadURL, params);
      this.video = filePath;
      return args.onSuccess({ code: 200 }, args.file);
    },

    handlePlayVideo(record) {
      this.videoVisible = true;
      this.selectRecord = record;
    },

    //打开删除框
    showdel(record) {
      this.deldata = record;
      this.isdel = true;
    },
    async handleDelete() {
         this.isdel = false
      let { status } = await this.http("delete", "/industry/delInspection", {
        industryId: this.check.id,
        inspectionId: this.deldata.id,
      });
      if (status === 1) {
        this.$message.success("删除成功!", 1);
        await this.getInspection();
        await this.getInspectList();
      } else {
        this.$message.error("删除失败!", 1);
      }
     
       //   this.$confirm({
      //     title: "系统提示",
      //     content: "确定要删除吗？",
      //     onOk: async () => {

      //     },
      //   });
    },
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },

    async getInspectList() {
      let {
        data: { data },
      } = await this.http("get", "/inspection/selectLikeList", {
        pageNo: 1,
        pageSize: 10000,
      });
      this.inspectlist = this.inspectList = (data || []).reduce((pre, cur) => {
        let index = this.data.findIndex((f) => f.id === cur.id);
        if (index === -1) {
          pre.push(cur);
        }
        return pre;
      }, []);
      console.log(this.inspectList);
    },
    handleFilterOption(inputValue, option) {
      return option.data.attrs.name.indexOf(inputValue) !== -1;
    },
    selectCheck() {
      let { selectedRowKeys } = this;
      if (this.selectedRowKeys.length <= 0) {
        this.$message.error("请先选择要操作的巡检");
        return false;
      }
      return true;
    },
    async handleSort(type) {
      if (this.selectCheck()) {
        let { selectedRowKeys } = this,
          selectId = selectedRowKeys[0];
        let findIndex = this.data.findIndex(
          (item) => Number(item.id) === Number(selectId)
        );
        if (findIndex !== -1) {
          let changeIndex = findIndex + type;
          if (changeIndex >= 0 && changeIndex <= this.data.length - 1) {
            await this.http("post", `inspection/update`, {
              ...this.data[findIndex],
              sort: this.data[changeIndex].sort,
            });
            await this.http("post", `inspection/update`, {
              ...this.data[changeIndex],
              sort: this.data[findIndex].sort,
            });
            // this.data[findIndex] = this.data.splice(changeIndex, 1, this.data[findIndex])[0]
            await this.getInspection();
            this.$message.success("排序成功", 1);
          }
        }
      }
    },
    // async handleSort(type){
    //     if(this.selectCheck()){
    //         let { selectedRowKeys } = this,
    //             selectId = selectedRowKeys[0]
    //             console.log(this.data)
    //         let findIndex = this.data.findIndex(item => Number(item.id) === Number(selectId))
    //         console.log("findIndex--->",findIndex)
    //         if(findIndex !== -1){
    //             let changeIndex = findIndex+type
    //             if(changeIndex >= 0 && changeIndex <= this.data.length - 1){
    //                 if(this.data[findIndex].sort == this.data[changeIndex].sort){
    //                     this.data[findIndex].sort = Number(this.data[findIndex].sort) + type
    //                 }else{
    //                     this.data[findIndex].sort = Number(this.data[changeIndex].sort) + type
    //                 }
    //                 let resp = await this.http("put", `inspection/update?id=${selectId}`, { sort: this.data[findIndex].sort })
    //                 // resp = await this.http("put", `inspection/update?id=${this.data[changeIndex].id}`, { sort:this.data[findIndex].sort })
    //                 // this.data[findIndex] = this.data.splice(changeIndex, 1, this.data[findIndex])[0]
    //                 await this.getDetail(this.$route.params.id);
    //                 this.$message.success('排序成功', 1);
    //             }
    //         }
    //     }
    // },
    handleShowAddCheck() {
      this.addCheckVisible = true;
    },
    async handleAddCheck() {
      if (!this.checkIds) {
        return this.$message.error("请选择对应巡检", 1);
      }
      let { status } = await this.http("post", "/industry/addInspection", {
        industryId: this.check.id,
        inspectionId: this.checkIds,
      });
      if (status === 1) {
        this.addCheckVisible = false;
        this.checkIds = undefined;
        this.keywords = undefined
        this.$message.success("添加成功!", 1);
        await this.getInspection();
        await this.getInspectList();
      } else {
        this.$message.error("添加失败!", 1);
      }
    },
    handleChange(page, size) {
      //列表展示条数改变
      this.pagination.current = page;
      this.pagination.pageSize = size;
      this.getInspection();
    },
    //监听input事件
    searchkey(){
       let timer = null
       clearTimeout(timer)
       setTimeout(()=>{
         this.searchinfo()
       },300)
         
    },

    //根据用户输入进行查询
      searchinfo(){
       this.inspectlist = this.inspectList.filter(item=>item.name.includes(this.keywords))

      },
      //选中当前巡检 
      subkey(keyword){
        this.keywords = keyword.name
        this.checkIds = keyword.id
      }
    
  },
  async mounted() {
    this.id = this.$route.params.id;
    await this.getDetail();
    await this.getInspection();
    await this.getInspectList();
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "../../assets/scss/mixin";

.header {
  @include fj();
  margin-bottom: 30px;
  .operate {
    .ant-btn + .ant-btn {
      margin-left: 40px;
    }
  }
}

.slide-fade-enter-active {
  transition: all 0.3s ease;
}
.slide-fade-leave-active {
  transition: all 0.3s ease;
}
.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateX(20px);
  opacity: 0;
}
.footer-wrap {
  display: flex;
  justify-content: flex-end;
}
#service-menu-search {
  .ant-input {
    width: 250px;
  }
}

.service-menu-query {
  @include fj(flex-start);
  .ant-form-item + .ant-form-item {
    margin-left: 10px;
  }
}
.delete-icon {
  cursor: pointer;
}
/deep/ .ant-upload-list-item-card-actions {
  .anticon-delete {
    color: #fff;
  }
}
.keywrod-wrap {
  height: 175px;
  border: 1px solid black;
  margin-top: 20px;
  overflow-y: auto;
  ul {
    li {
      cursor: pointer;
      height: 35px;
      line-height: 30px;
      font-size: 13px;
      padding: 0 10px;
      transition: all 1.2s;
    }
    li:hover {
      background-color: #fff;
      color: black;
      opacity: 0.5;
    }
  }
}
.clearfix::after {
  display: block;
  content: "";
  clear: both;
}
</style>